//
//  NSString+Helper.m
//  Live
//
//  Created by Heller on 16/4/21.
//  Copyright © 2016年 Heller. All rights reserved.
//

#import "NSString+Helper.h"
#import "BNDOfficeDocKit.h"


@implementation NSString (Helper)

+ (CGSize)lk_sizeWithText:(NSString *)text {
    return [text boundingRectWithSize:CGSizeMake(kDeviceWidth - 150, MAXFLOAT)
                              options:NSStringDrawingUsesLineFragmentOrigin
                           attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]}
                              context:nil].size;
}


+(NSString*)lk_getTimeStrStyleWithTimeInterval:(long long)time
{
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:time];
    return [NSString lk_getTimeStrStyleWithDate:date];
}

+(NSString*)lk_getTimeStrStyleWithDate:(NSDate *)date
{
    if(!date){
        return @"";
    }
    
    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear |NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekOfMonth|NSCalendarUnitWeekday;
    NSDateComponents * component=[calendar components:unitFlags fromDate:date];
    
    int year=(int)[component year];
    int month=(int)[component month];
    int day=(int)[component day];
    int hour=(int)[component hour];
    int minute=(int)[component minute];
    int week= (int)[component weekOfMonth];
    int weekday=(int)[component weekday];
    
    NSDate * today=[NSDate date];
    component=[calendar components:unitFlags fromDate:today];
    
    int t_year=(int)[component year];
    int t_month=(int)[component month];
    int t_day=(int)[component day];
    int t_week=(int)[component weekOfMonth];
    
    NSString*string=nil;
    if(year==t_year&&month==t_month&&day==t_day)
    {
        if(hour<6&&hour>=0)
            string=[NSString stringWithFormat:@"%d:%02d",hour,minute];
        else if(hour>=6&&hour<12)
            string=[NSString stringWithFormat:@"%d:%02d",hour,minute];
        else if(hour>=12&&hour<18)
            string=[NSString stringWithFormat:@"%d:%02d",hour,minute];
        else
            string=[NSString stringWithFormat:@"%d:%02d",hour,minute];
    }
    else if((t_day -day) ==1)
    {
        if(hour<6&&hour>=0)
            string= @"昨天";
        //[NSString stringWithFormat:@"昨天"];
        //,hour,minute];
        else if(hour>=6&&hour<12)
            string= @"昨天";
        //[NSString stringWithFormat:@"昨天 %d:%02d",hour,minute];
        else if(hour>=12&&hour<18)
            string= @"昨天";
        //[NSString stringWithFormat:@"昨天 %d:%02d",hour,minute];
        else
            string= @"昨天";
        //[NSString stringWithFormat:@"昨天 %d:%02d",hour,minute];
        
    }
    else if(year==t_year&&week==t_week)
    {
        NSString * daystr=nil;
        switch (weekday) {
            case 1:
                daystr=@"日";
                break;
            case 2:
                daystr=@"一";
                break;
            case 3:
                daystr=@"二";
                break;
            case 4:
                daystr=@"三";
                break;
            case 5:
                daystr=@"四";
                break;
            case 6:
                daystr=@"五";
                break;
            case 7:
                daystr=@"六";
                break;
            default:
                break;
        }
        string=[NSString stringWithFormat:@"星期%@ ",daystr];
        //%02d",daystr,hour,minute];
    }
    else if(year==t_year)
        string=[NSString stringWithFormat:@"%d月%d日",month,day];
    else
        string=[NSString stringWithFormat:@"%d年%d月%d日",year,month,day];
    
    return string;
}

+(NSString*)lk_getTimeStrStyleWithBirthdayDate:(NSDate *)date
{
    if(!date){
        return @"";
    }
    
    NSCalendar * calendar=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitYear |NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekOfMonth|NSCalendarUnitWeekday;
    NSDateComponents * component=[calendar components:unitFlags fromDate:date];
    
    int month=(int)[component month];
    int day=(int)[component day];
    
    NSString  *string=[NSString stringWithFormat:@"%d月%d日",month,day];
    
    return string;
}

//是否含有表情
+(BOOL)lk_stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        const unichar hs = [substring characterAtIndex:0];
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (substring.length > 1) {
                const unichar ls = [substring characterAtIndex:1];
                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    returnValue = YES;
                }
            }
        } else if (substring.length > 1) {
            const unichar ls = [substring characterAtIndex:1];
            if (ls == 0x20e3) {
                returnValue = YES;
            }
        } else {
            if (0x2100 <= hs && hs <= 0x27ff) {
                returnValue = YES;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                returnValue = YES;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                returnValue = YES;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                returnValue = YES;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                returnValue = YES;
            }
        }
    }];
    
    return returnValue;
}

+ (NSString *)lk_stringWithChangeCountString:(NSString *)countString{
    NSInteger num = [countString integerValue];
    NSString *result = countString;
    if(num >= 10000){
        result = [NSString stringWithFormat:@"%.1fw", num / 10000.0];
    }else  if(num >= 1000){
        result = [NSString stringWithFormat:@"%.1fk", num / 1000.0];
    }else {
        result = [NSString stringWithFormat:@"%.1ld", (long)num];
    }
    return result;
}


+ (NSString *)lk_timeAndcontent
{
    NSDate *datenow = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:datenow];
    NSDate *localeDate = [datenow  dateByAddingTimeInterval: interval];
    NSString *timeSp = [NSString stringWithFormat:@"%lld", (long long)[localeDate timeIntervalSince1970]];
    return timeSp;
}


+ (NSString *)lk_titleLiveAndShare
{
    NSArray * titleArray = [NSArray arrayWithObjects:@"美味生活，就在滋味LIVE",@"来滋味Live，遇见最美的生活方式",@"来滋味Live，与美味生活不期而遇",@"生活妙不可言，就在滋味Live", nil];
    
    uint32_t j = arc4random() % 3;
    NSString * title = titleArray[j];
    
    return title;
    
}

//判断是否为整形：
- (BOOL)lk_isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形：

- (BOOL)lk_isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

- (BOOL)lk_isNumber {
    
    if([self lk_isPureInt:self] || [self lk_isPureFloat:self]) {
        return YES;
    }else {
        return NO;
    }
}

- (NSString *)lk_likeCount {
    
    NSInteger num = [self integerValue];
    NSString *result;
    if(num >= 10000){
        result = [NSString stringWithFormat:@"%.2fw", num / 10000.0];
    }else if (num > 1000){
        result = [NSString stringWithFormat:@"%.2fk", num / 1000.0];
    }else{
        result = [NSString stringWithFormat:@"%@", self];
    }
    return result;
}

- (NSString *)lk_numberToTime {
    
    NSDateFormatter *selectDateFormatter = [[NSDateFormatter alloc] init];
    selectDateFormatter.dateFormat = @"MM.dd HH:mm";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self integerValue]];
    return  [selectDateFormatter stringFromDate:date];
}

- (NSString *)lk_secondToTime {
    
    NSInteger second = [self integerValue];
    NSInteger hour = second / 3600;  // 多少个小时
    
    NSInteger residueSecond = second - hour * 3600;
    NSInteger min = residueSecond / 60;
    
    residueSecond = residueSecond - min * 60;
    
    if(hour > 0) {
        return [NSString stringWithFormat:@"%zd:%02zd:%02zd", hour, min, residueSecond];
    }else{
        return [NSString stringWithFormat:@"%02zd:%02zd", min, residueSecond];
    }
}

- (NSString *)lk_getNowTimeTimestamp {
    
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", a];
    
    return timeString;
}

- (NSString *)lk_secondToTimeSinceNow {
    
    NSInteger second = [self integerValue];
    
    NSInteger threeDay      = second / 3600 / 24 / 3;  // 3天
    NSInteger lessThreedays = second / 3600 / 24;  // 天
    NSInteger hour          = second / 3600;  // 多少个小时
    
    NSInteger residueSecond = second - hour * 3600;
    NSInteger min           = residueSecond / 60;
    
    residueSecond = residueSecond - min * 60;
    
    if (threeDay > 0) {
        return @"3天前";
    } else if (lessThreedays > 0) {
        return [NSString stringWithFormat:@"%zd天前", lessThreedays];
    } else if (hour > 0) {
        return [NSString stringWithFormat:@"%zd小时前", hour];
    } else {
        return [NSString stringWithFormat:@"%ld分前", min+1]; // +1:1分钟内
    }
}

- (NSString *)lk_lastTwoPathComponent {
    
    NSString *last = [self lastPathComponent];
    NSString *temp = [self stringByDeletingLastPathComponent];
    NSString *second = [temp lastPathComponent];
    
    if(last.length > 0 && second.length > 0) {
        return  [NSString stringWithFormat:@"%@/%@", second, last];
    }else{
        return nil;
    }
}

+ (NSMutableAttributedString *)lk_formatStringToUpDownAttribute:(NSString *)formatString FormatStringlength:(NSUInteger)FormatStringlength {
    NSMutableAttributedString *text = [NSMutableAttributedString new];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formatString];
    NSInteger totalLen = formatString.length;
    
    NSRange amountRange = NSMakeRange(0, totalLen - FormatStringlength - 1);
    NSRange titleRange = NSMakeRange(totalLen - FormatStringlength, FormatStringlength);
    [attributedString setColor:UIColorWithHex(0xffffff) range:amountRange];
    [attributedString setColor:UIColorHexAndAlpha(0xffffff, 0.8) range:titleRange];
    [attributedString setFont:BNDPFHeavyFont(16) range:amountRange];
    [attributedString setFont:BNDPFRegularFont(12) range:titleRange];
    [text appendAttributedString:attributedString];
    [text setAlignment:NSTextAlignmentCenter];
    [text setLineSpacing:4];
    
    return text;
}

- (NSAttributedString *)lk_topicStringFontSize:(CGFloat)size
{
    NSString *topic = [NSString stringWithFormat:@"#%@#", self];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:topic];
    [attributedString setColor:UIColorHex(0xff950b)];
    [attributedString setFont:BNDPFRegularFont(size)];
    [attributedString setColor:UIColorWithHex(0x333333) range:NSMakeRange(1, self.length)];
    return attributedString;
}


+ (BOOL)isUrlAddress:(NSString *)url
{
    NSString *reg = @"/^(http|https)://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$/";
    NSPredicate *urlPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
    return [urlPredicate evaluateWithObject:url];
}

+ (NSMutableAttributedString *)formatStringToUserIDAttribute:(NSString *)formatString
{
    NSMutableAttributedString *text = [NSMutableAttributedString new];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formatString];
    NSInteger totalLen = formatString.length;
    
    NSRange amountRange = NSMakeRange(0, totalLen);
    [attributedString setColor:UIColorHex(0xe5e5e5) range:amountRange];
    [attributedString setFont:BNDPFRegularFont(12) range:amountRange];
    
    
    UIImage *image = BNDImageNamed(@"mine_icon_id");
    NSMutableAttributedString *attachImage = [NSMutableAttributedString attachmentStringWithContent:image
                                                                                        contentMode:UIViewContentModeCenter
                                                                                     attachmentSize:image.size
                                                                                        alignToFont:BNDPFRegularFont(12)
                                                                                          alignment:YYTextVerticalAlignmentCenter];
    
    [text appendAttributedString:attachImage];
    [text appendAttributedString:[[NSMutableAttributedString alloc] initWithString:@" "]];
    [text appendAttributedString:attributedString];
    [text setAlignment:NSTextAlignmentCenter];
    return text;
}

/**
 判断一个数字是否小于num
 */
- (BOOL)lk_isLessThanAndEqual:(double)num
{
    return [self doubleValue] <= num;
}


/**
 判断小数点后面是否小于多少位
 */
- (BOOL)lk_isLessThanDecimalAndEqual:(NSInteger)num
{
    
    NSArray *strings = [self componentsSeparatedByString:@"."];
    if(strings.count < 2)
    {
        return YES;
    }else
    {
        NSString *string = strings.lastObject;
        return string.length <= num;
    }
}

- (unsigned long long)lk_fileSize
{
    // 总大小
    unsigned long long size = 0;
    
    // 文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // 文件属性
    NSDictionary *attrs = [mgr attributesOfItemAtPath:self error:nil];
    
    if ([attrs.fileType isEqualToString:NSFileTypeDirectory]) { // 文件夹
        // 获得文件夹的大小  == 获得文件夹中所有文件的总大小
        NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self];
        for (NSString *subpath in enumerator) {
            // 全路径
            NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
            // 累加文件大小
            size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
        }
    } else { // 文件
        size = attrs.fileSize;
    }
    
    return size;
}


+ (NSString *)lk_valueFoKey:(NSString *)key OfwebAddress:(NSString *)webaddress
{
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",key];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags options:NSRegularExpressionCaseInsensitive error:&error];
    
    NSArray *matches = [regex matchesInString:webaddress
                                      options:0
                                        range:NSMakeRange(0, [webaddress length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [webaddress substringWithRange:[match rangeAtIndex:2]];
        return tagValue;
    }
    return @"";
}

//- (NSString *)lk_urlAppendTimeStamp
//{
//    NSInteger timeStamp = [[NSDate date] utcTimeStamp];
//    return [self stringByAppendingFormat:@"&v=%zd", timeStamp];
//}

- (NSString *)lk_formURLEncodedString
{
    if (self.length == 0) {
        return self;
    }
    
    NSString *unreserved = @"-._~";
    NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowed addCharactersInString:unreserved];
    [allowed addCharactersInString:@" "];
    
    NSString *encodeValue = [self stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    encodeValue = [encodeValue stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    
    return encodeValue;
}


- (CGSize)stringSizeWithFont:(UIFont *)font contraintHeight:(CGFloat)height
{
    CGSize size;
    
    
    CGSize contraintSize = CGSizeMake(CGFLOAT_MAX,height);
    
    
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    
    size = [self boundingRectWithSize:contraintSize  options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
    
    
    return CGSizeMake(ceilf(size.width), ceilf(size.height));
    
}

/**
 判断输入的字符串是否为空或者为nil
 
 @param string 需要判断的字符串
 
 @return 返回YES或NO
 */
+ (BOOL)isEmpty:(NSString *)string
{
    if([string isEqual:[NSNull null]])
    {
        return YES;
    }
    
    if(string == nil)
    {
        return YES;
    }
    
    if(string == NULL)
    {
        return YES;
    }
    
    if([string stringByReplacingOccurrencesOfString:@" " withString:@""].length == 0)
    {
        return YES;
    }
    else if ([string stringByReplacingOccurrencesOfString:@"\n" withString:@""].length == 0)
    {
        return YES;
    }
    return NO;
}


+(NSString *)getAstroWithMonth:(NSInteger)m day:(NSInteger)d
{
    
    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    NSString *astroFormat = @"102123444543";
    NSString *result;
    
    if (m<1||m>12||d<1||d>31){
        return @"错误日期格式!";
    }
    
    if(m==2 && d>29)
    {
        return @"错误日期格式!!";
    }else if(m==4 || m==6 || m==9 || m==11) {
        
        if (d>30) {
            return @"错误日期格式!!!";
        }
    }
    
    result=[NSString stringWithFormat:@"%@座",[astroString substringWithRange:NSMakeRange(m*2-(d < [[astroFormat substringWithRange:NSMakeRange((m-1), 1)] intValue] - (-19))*2,2)]];
    
    
    return result;
    
}

/**获取字符串所占位置大小
 *@param font 字符串要显示的字体
 *@param width 每行最大宽度
 *@return 字符串大小
 */
- (CGSize)stringSizeWithFont:(UIFont*) font contraintWith:(CGFloat) width
{
    CGSize size;
    
    
    CGSize contraintSize = CGSizeMake(width,CGFLOAT_MAX);
    
    
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    
    size = [self boundingRectWithSize:contraintSize  options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
    
    
    return CGSizeMake(ceilf(size.width), ceilf(size.height));
}

#pragma mark --验证--
- (BOOL)isMobileNumber
{
    
    if(self.length != 11)
    {
        return NO;
    }
    //手机号码
    NSString * mobile = @"^1[0-9][0-9]{9}$";
    //中国移动
    NSString *CM = @"^1(3[4-9]|5[012789]|8[278])\\d{8}$";
    //中国联通
    NSString *CU = @"^1(3[0-2]|5[56]|8[56])\\d{8}$";
    //中国电信
    NSString *CT = @"^(180|189|133|134|153)\\d{10}$";
    
    //设定断言
    NSPredicate *regextestMobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",mobile];
    NSPredicate *regextestCM = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CM];
    NSPredicate *regextestCU = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CU];
    NSPredicate *regextestCT = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CT];
    
    if(([regextestMobile evaluateWithObject:self] == YES) ||
       ([regextestCM evaluateWithObject:self] == YES) ||
       ([regextestCU evaluateWithObject:self] == YES) ||
       ([regextestCT evaluateWithObject:self] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//判断是不是纯数字
- (BOOL)isNumText
{
    if([self stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]].length)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}


+ (NSString*)handleOfficeDocContent:(NSString*)aStr
{
    NSString* aStr1 = [self getZZwithString:aStr];
    NSString *content = [aStr1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *  string =[content stringByReplacingOccurrencesOfString:@"\n"withString:@""];
    NSString *  string1 =[string stringByReplacingOccurrencesOfString:@"\t"withString:@" "];
    NSString *  string3 =[string1 stringByReplacingOccurrencesOfString:@"<br>"withString:@" "];
    NSString *  string2 =[string3 stringByReplacingOccurrencesOfString:@"\U00002028"withString:@""];
    return string2;
}


+ (NSString *)getZZwithString:(NSString *)string
{
    NSRegularExpression *regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n"
                                                                                    options:0
                                                                                      error:nil];
    string=[regularExpretion stringByReplacingMatchesInString:string options:NSMatchingReportProgress range:NSMakeRange(0, string.length) withTemplate:@""];
    
    return string;
}
@end
